package ai.tuobot.sdk.util

class CircularBuffer(size: Int) {
    private val buffer = ByteArray(size)
    private var writeIndex = 0
    private var readIndex = 0
    private var isFull = false

    fun write(data: ByteArray) {
        for (byte in data) {
            buffer[writeIndex] = byte
            writeIndex = (writeIndex + 1) % buffer.size
            if (writeIndex == readIndex && !isFull) {
                isFull = true
            }else if (isFull) {
                readIndex = writeIndex
            }
        }
    }

    fun read(output: ByteArray, length: Int): Int {
        var bytesRead = 0
        while (bytesRead < length && (readIndex != writeIndex || isFull) && buffer.size >= length) {
            output[bytesRead] = buffer[readIndex]
            readIndex = (readIndex + 1) % buffer.size
            bytesRead++
            isFull = false  // 读取数据后，标记为未满
        }
        return bytesRead
    }

    fun isEmpty(): Boolean {
        return !isFull && (readIndex == writeIndex)
    }
}